<template>
  <div class="reception-medical-container">
    <div class="header">
      <h2>健康档案管理</h2>
      <p>查看和管理所有老人的健康档案记录</p>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-card shadow="never">
        <el-form :model="searchForm" inline>
          <el-form-item label="老人姓名">
            <el-input
              v-model="searchForm.elderName"
              placeholder="请输入老人姓名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="记录类型">
            <el-select
              v-model="searchForm.recordType"
              placeholder="请选择记录类型"
              clearable
              style="width: 200px"
            >
              <el-option label="日常检查" value="日常检查" />
              <el-option label="血糖监测" value="血糖监测" />
              <el-option label="血压监测" value="血压监测" />
              <el-option label="心脏检查" value="心脏检查" />
              <el-option label="其他检查" value="其他检查" />
            </el-select>
          </el-form-item>
          <el-form-item label="记录时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-card shadow="never">
        <el-table
          :data="tableData"
          v-loading="loading"
          style="width: 100%"
          :default-sort="{ prop: 'recordTime', order: 'descending' }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="elderName" label="老人姓名" width="120" align="center" />
          <el-table-column prop="recordType" label="记录类型" width="120" align="center" />
          <el-table-column prop="bodyTemperature" label="体温(℃)" width="100" align="center">
            <template #default="{ row }">
              {{ row.bodyTemperature || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="bloodPressure" label="血压" width="120" align="center">
            <template #default="{ row }">
              {{ row.bloodPressure || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="heartRate" label="心率" width="80" align="center">
            <template #default="{ row }">
              {{ row.heartRate || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="bloodSugar" label="血糖" width="80" align="center">
            <template #default="{ row }">
              {{ row.bloodSugar || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="recordTime" label="记录时间" width="180" align="center" sortable>
            <template #default="{ row }">
              {{ formatDateTime(row.recordTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="caregiverName" label="负责护工" width="120" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                size="small"
                @click="handleViewDetail(row)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="健康档案详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentRecord" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录ID">
            {{ currentRecord.medicalId }}
          </el-descriptions-item>
          <el-descriptions-item label="老人姓名">
            {{ currentRecord.elderName }}
          </el-descriptions-item>
          <el-descriptions-item label="记录类型">
            {{ currentRecord.recordType }}
          </el-descriptions-item>
          <el-descriptions-item label="记录时间">
            {{ formatDateTime(currentRecord.recordTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="体温">
            {{ currentRecord.bodyTemperature ? currentRecord.bodyTemperature + '℃' : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="血压">
            {{ currentRecord.bloodPressure || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="心率">
            {{ currentRecord.heartRate ? currentRecord.heartRate + '次/分' : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="血糖">
            {{ currentRecord.bloodSugar ? currentRecord.bloodSugar + 'mmol/L' : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="负责护工">
            {{ currentRecord.caregiverName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRecord.status)" size="small">
              {{ getStatusText(currentRecord.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider>详细描述</el-divider>
        <div class="description-section">
          <p>{{ currentRecord.description || '无详细描述' }}</p>
        </div>

        <el-divider v-if="currentRecord.diagnosis">诊断信息</el-divider>
        <div v-if="currentRecord.diagnosis" class="diagnosis-section">
          <p>{{ currentRecord.diagnosis }}</p>
        </div>

        <el-divider v-if="currentRecord.treatment">治疗方案</el-divider>
        <div v-if="currentRecord.treatment" class="treatment-section">
          <p>{{ currentRecord.treatment }}</p>
        </div>

        <el-divider v-if="currentRecord.medication">用药情况</el-divider>
        <div v-if="currentRecord.medication" class="medication-section">
          <p>{{ currentRecord.medication }}</p>
        </div>

        <el-divider v-if="currentRecord.doctorName">医生信息</el-divider>
        <div v-if="currentRecord.doctorName" class="doctor-section">
          <p><strong>医生姓名：</strong>{{ currentRecord.doctorName }}</p>
          <p v-if="currentRecord.hospitalName"><strong>医院名称：</strong>{{ currentRecord.hospitalName }}</p>
          <p v-if="currentRecord.followUpDate"><strong>复诊时间：</strong>{{ formatDate(currentRecord.followUpDate) }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getMedicalRecords } from '@/api/medical'

// 搜索表单
const searchForm = reactive({
  elderName: '',
  recordType: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentRecord = ref(null)

// 状态映射
const statusMap = {
  'active': { text: '有效', type: 'success' },
  'inactive': { text: '无效', type: 'info' },
  'pending': { text: '待处理', type: 'warning' },
  'completed': { text: '已完成', type: 'success' }
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status]?.text || status
}

// 获取状态类型
const getStatusType = (status) => {
  return statusMap[status]?.type || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  loadTableData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    elderName: '',
    recordType: '',
    dateRange: []
  })
  pagination.currentPage = 1
  loadTableData()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadTableData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadTableData()
}

// 查看详情
const handleViewDetail = (record) => {
  currentRecord.value = record
  detailDialogVisible.value = true
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      elderName: searchForm.elderName,
      recordType: searchForm.recordType,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }

    const response = await getMedicalRecords(params)
    if (response.code === 200) {
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取健康档案数据失败:', error)
    ElMessage.error('获取数据失败')
    // 模拟数据
    tableData.value = [
      {
        medicalId: 1,
        elderName: '张大爷',
        recordType: '日常检查',
        bodyTemperature: 36.5,
        bloodPressure: '120/80',
        heartRate: 75,
        bloodSugar: 5.6,
        recordTime: '2024-10-03 08:00:00',
        caregiverName: '张护工',
        status: 'active',
        description: '身体状况良好，各项指标正常',
        diagnosis: '健康状况良好',
        treatment: '常规保健',
        medication: '降压药每日一次',
        doctorName: '王医生',
        hospitalName: '中心医院',
        followUpDate: '2024-12-31'
      },
      {
        medicalId: 2,
        elderName: '李大妈',
        recordType: '血压监测',
        bodyTemperature: 36.8,
        bloodPressure: '130/85',
        heartRate: 80,
        bloodSugar: 6.2,
        recordTime: '2024-10-03 08:15:00',
        caregiverName: '李护工',
        status: 'active',
        description: '血压稍高，需注意观察',
        diagnosis: '轻度高血压',
        treatment: '调整用药剂量',
        medication: '降压药每日两次',
        doctorName: '李医生',
        hospitalName: '人民医院',
        followUpDate: '2024-11-30'
      }
    ]
    pagination.total = tableData.value.length
  } finally {
    loading.value = false
  }
}

// 初始化加载
onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.reception-medical-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.header {
  margin-bottom: 20px;
  text-align: center;
}

.header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.header p {
  margin: 8px 0 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}

.description-section,
.diagnosis-section,
.treatment-section,
.medication-section,
.doctor-section {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.description-section p,
.diagnosis-section p,
.treatment-section p,
.medication-section p,
.doctor-section p {
  margin: 0;
  line-height: 1.6;
  color: #606266;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-divider) {
  margin: 20px 0;
}
</style>
